﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using IRC.IRepairClouds.DataLayer;
using System.Data.Objects;

namespace IRC.IRepairClouds.WebClient
{
    public class MembershipProvider : System.Web.Security.MembershipProvider
    {
        private static class CompiledQueries
        {
            public static readonly Func<ICloudRepairEntities, string, EUser> GetUserByUsername =
                CompiledQuery.Compile<ICloudRepairEntities, string, EUser>(
                    (db, username) => (from u in db.Users
                                       where u.Login.ToLower() == username.ToLower()
                                       select u).FirstOrDefault()
                );

            public static readonly Func<ICloudRepairEntities, Guid, EUser> GetUserById =
                CompiledQuery.Compile<ICloudRepairEntities, Guid, EUser>(
                    (db, userId) => (from u in db.Users
                                     where u.ID == userId
                                     select u).FirstOrDefault()
                );

            public static readonly Func<ICloudRepairEntities, string, string, bool> ValidateUser =
                CompiledQuery.Compile<ICloudRepairEntities, string, string, bool>(
                    (db, username, password) => (from u in db.Users
                                                 where u.Active == 1 && u.Login.ToLower() == username.ToLower() && u.Password == password
                                                 select u).Count() > 0
                );
        }

        public override string ApplicationName
        {
            get { throw new NotSupportedException(); }
            set { throw new NotSupportedException(); }
        }

        public override bool EnablePasswordReset
        {
            get { return false; }
        }

        public override bool EnablePasswordRetrieval
        {
            get { return false; }
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { return 0; }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return 0; }
        }

        public override int MinRequiredPasswordLength
        {
            get { return 0; }
        }

        public override int PasswordAttemptWindow
        {
            get { return 0; }
        }

        public override System.Web.Security.MembershipPasswordFormat PasswordFormat
        {
            get { return System.Web.Security.MembershipPasswordFormat.Clear; }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { return string.Empty; }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { return false; }
        }

        public override bool RequiresUniqueEmail
        {
            get { return false; }
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            throw new NotSupportedException();
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotSupportedException();
        }

        public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            throw new NotSupportedException();
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotSupportedException();
        }

        public override System.Web.Security.MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotSupportedException();
        }

        public override System.Web.Security.MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotSupportedException();
        }

        public override System.Web.Security.MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotSupportedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotSupportedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotSupportedException();
        }

        public override System.Web.Security.MembershipUser GetUser(string username, bool userIsOnline)
        {
            using (ICloudRepairEntities db = new ICloudRepairEntities())
            {
                var user = CompiledQueries.GetUserByUsername(db, username);
                if (user == null)
                    return null;
                return GetUser(user);
            }
        }

        private System.Web.Security.MembershipUser GetUser(EUser user)
        {
            return new MembershipUserEx(user, this.Name, user.Login, user.ID, null, null, null, true,
                user.Active != 1, user.CreatedAt, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.MinValue);
        }

        public override System.Web.Security.MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            if (!(providerUserKey is Guid))
                return null;
            Guid userId = (Guid)providerUserKey;
            using (ICloudRepairEntities db = new ICloudRepairEntities())
            {
                var user = CompiledQueries.GetUserById(db, userId);
                if (user == null)
                    return null;
                return GetUser(user);
            }
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new NotSupportedException();
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotSupportedException();
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotSupportedException();
        }

        public override void UpdateUser(System.Web.Security.MembershipUser user)
        {
            throw new NotSupportedException();
        }

        public override bool ValidateUser(string username, string password)
        {
            using (ICloudRepairEntities db = new ICloudRepairEntities())
            {
                return CompiledQueries.ValidateUser(db, username, password);
            }
        }
    }
}